//
//  FeedbackViewController.m
//  ERP
//
//  Created by goldeney on 15/4/1.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "FeedbackViewController.h"

#import "GEPickerTextField.h"
#import "GEObjectButton.h"
#import "GEInputTableViewCell.h"

#import "FileUploadModel.h"
#import "FileSizeFormatHelper.h"
#import "FileTypeIcon.h"
#import "UploadViewController.h"
#import "PreviewLocalFileHelper.h"

#import "ServiceConnect.h"
#import "UserLoginNSCoding.h"
#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

@interface FeedbackViewController()

@property (nonatomic, strong) NSMutableArray *accessoryArray;

@end


@implementation FeedbackViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"意见反馈"];
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self
                                                                      action:@selector(uploadFeedbackSelector:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.accessoryArray = [NSMutableArray array];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark
#pragma mark - 发送消息

- (void)uploadFeedbackSelector:(id)selector
{
    //关闭键盘
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    GEPickerTextField *textField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:0];
    NSDictionary *briefcaseType = textField.selectData;
    
    UITextView *FeedbackField = [self.tableView getCellSaveClass:[UITextView class] pathForRow:0 inSection:2];
    NSString *Feedback = [FeedbackField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (!(briefcaseType && briefcaseType.count>0)) {
        [self showAlertView:@"请选择意见或建议类型"];
    } else if (Feedback.length <= 0){
        [self showAlertView:@"请输入意见或建议内容"];
    } else {
        //发送消息
        [self getNetWorkDataFeedbackSend:Feedback];
    }
}

- (void)getNetWorkDataFeedbackSend:(NSString*)Feedback
{
    //获取用户信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    
    //反馈类型
    GEPickerTextField *textField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:0];
    NSDictionary *briefcaseType = textField.selectData;
    
    //处理附件信息
    NSString *jsonFileString = nil;
    NSMutableArray *jsonFileArray = [NSMutableArray array];
    for(FileUploadModel *model in self.accessoryArray){
        NSDictionary *jsonDictionary = [model getFileInfo];
        NSMutableDictionary *mDictionary = [NSMutableDictionary dictionary];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"filePath"] forKey:@"FJPath"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"fileName"] forKey:@"FJName"];
        [jsonFileArray addObject:mDictionary];
    }
    if ([NSJSONSerialization isValidJSONObject:jsonFileArray]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonFileArray options:NSJSONWritingPrettyPrinted error:&error];
        jsonFileString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    ServiceParametModel *wbsModel = [[ServiceParametModel alloc] init];
    [wbsModel setValue:userInfo.Id forKey:@"userid"];
    [wbsModel setValue:[briefcaseType objectFormatForKey:@"dm"] forKey:@"FeedbackType"];
    [wbsModel setValue:Feedback forKey:@"FbValue"];
    [wbsModel setValue:jsonFileString forKey:@"FeedbackFjJsonData"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_Feedback_Submitted" dataArray:wbsModel];
    [content showMBProgressHUD:self.navigationController labelText:@"正在提交"];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(result.resultArray && result.resultArray.count>0){
            //result：返回结果(1成功，0失败)
            NSDictionary *resultArray = [result.resultArray firstObject];
            NSInteger result = [[resultArray objectFormatForKey:@"result"] integerValue];
            if (result == 0) [self showAlertView:@"意见或建议提交失败，请重新尝试"];
            else [self successUpLoadFeedback];
            
        } else {
            [self showAlertView:@"意见或建议提交失败，请重新尝试"];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"==failed===%@",error);
        [self showAlertView:@"提交出错了，请重新尝试"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===abnormal==%@",error);
        [self showAlertView:@"没有连接网络，请检查网络是否连接"];
    }];
}

#pragma mark -
#pragma mark Get UITableViewCell

- (id)getCellClass:(Class)mClass pathForRow:(NSInteger)row inSection:(NSInteger)section
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
    UITableViewCell *tableCell = [self.tableView cellForRowAtIndexPath:indexPath];
    for (id view in tableCell.contentView.subviews) {
        if ([view isKindOfClass:mClass]) {
            return view;
        }
    }
    return nil;
}

- (void)successUpLoadFeedback
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的意见或建议已提交成功，我们将尽快处理您的意见，感谢您的支持与厚爱！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}


#pragma mark
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 1) return self.accessoryArray.count + 1;
    else return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"OAUploadFeedbackViewCell%ld%ld",indexPath.section,indexPath.row];
    if(indexPath.section == 0){
        GEInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell != nil) return cell;
        
        //获取意见反馈类型
        ServiceParametModel *model = [[ServiceParametModel alloc] init];
        model.methodName = @"OA_PublicDictionaryType";
        [model setValue:@1 forKey:@"type"];
        
        cell = [[GEInputTableViewCell alloc] initWithSelectReuseIdentifier:CellIdentifier model:model];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.titleName = @"反馈类型";
        cell.placeholder = @"请选择反馈类型";
        cell.isMark = YES;
        [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
        return cell;
    }
    
    //添加附件
    else if(indexPath.section == 1){
        GEInputTableViewCell *cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.bounds = CGRectMake(0, 0, cell.bounds.size.width, 48);
        
        if (indexPath.row < self.accessoryArray.count) {
            FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
            [self drawRowFileCell:cell model:model indexPath:indexPath];
        } else {
            UIImage *image = [UIImage imageNamed:@"button_bg_add"];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.frame.size.width/2-image.size.width/2, cell.frame.size.height/2-image.size.height/2, image.size.width, image.size.height)];
            [imageView setImage:image];
            [cell.contentView addSubview:imageView];
        }
        return cell;
    }
    
    //消息内容
    else if(indexPath.section == 2){
        GEInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryNone;
            UITextView *field = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, cell.contentView.frame.size.width - 25, 170)];
            field.font = [UIFont systemFontOfSize:15.0];
            field.textColor = [UIColor darkGrayColor];
            field.textAlignment = NSTextAlignmentLeft;
            [cell.contentView addSubview:field];
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
        }
        return cell;
    }
    
    return nil;
}

//添加文件
- (void)drawRowFileCell:(UITableViewCell*)cell model:(FileUploadModel *)model indexPath:(NSIndexPath *)indexPath
{
    CGSize cellSize = cell.frame.size;
    cellSize.height = 50;
    cellSize.width = SuperWidth;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, cellSize.height - 10, cellSize.height - 10)];
    imageView.image = [FileTypeIcon setFileTypeIcon:model.filePath];
    [cell.contentView addSubview:imageView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, 3, cellSize.width - cellSize.height - 60, cellSize.height/2)];
    titleLabel.text = model.fileName;
    titleLabel.font = [UIFont systemFontOfSize:15.0];
    titleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:titleLabel];
    
    NSString *fileSize = [FileSizeFormatHelper getFileSizeString:[NSString stringWithFormat:@"%lld",model.fileSize]];
    UILabel *field = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, cellSize.height/2 - 2, cellSize.width - cellSize.height - 10, cellSize.height/2)];
    field.font = [UIFont systemFontOfSize:12.0];
    field.text = [NSString stringWithFormat:@"文件大小：%@", fileSize] ;
    field.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:field];
    
    GEObjectButton *button = [GEObjectButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(cellSize.width - 70, 0, cellSize.height, cellSize.height);
    [button setImage:[UIImage imageNamed:@"del.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(delFileSelector:) forControlEvents:UIControlEventTouchUpInside];
    button.object = @[@(indexPath.section), model];
    [cell.contentView addSubview:button];
    
    //添加分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 1, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [cell.contentView addSubview:lineView];
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //基本信息不添加
    if(section == 0) return nil;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView *viewBackground = [[UIView alloc] initWithFrame:CGRectMake(10, 0, SuperWidth - 20, 30)];
    viewBackground.backgroundColor = [UIColor whiteColor];
    [view addSubview:viewBackground];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SuperWidth - 30, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    if (section == 1) {
        lable.text = @"添加附件";
    } else if(section == 2){
        lable.text = @"意见或建议内容";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) return 0;
    else return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) return 44;
    else if (indexPath.section == 1) return 50;
    else return 180;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //反馈类型
    if(indexPath.section == 0 && indexPath.row == 0) {
        GEInputTableViewCell *geViewCell = (GEInputTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        NSArray *resultArray = geViewCell.objectData;
        
        if (resultArray) {
            NSDictionary *QDDJ = [NSDictionary dictionaryWithObject:@"%@" forKey:@"mc"];
            [geViewCell setPickerTextFieldComponents:resultArray keyValue:@[QDDJ]];
        } else {
            [geViewCell reloadData];
        }
    }
    
    //添加附件
    else if (indexPath.section == 1 && indexPath.row ==([self tableView:nil numberOfRowsInSection:1] - 1)) {
        UploadViewController *abstractView = [[UploadViewController alloc] init];
        [abstractView setNumberType:@"2" extension:nil];
        
        abstractView.key = @"AccessoryFile";
        abstractView.backResultDelagate = self;
        [self.navigationController pushViewController:abstractView animated:YES];
    }
    
    //附件预览
    else if (indexPath.section == 1){
        FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
        PreviewLocalFileHelper *preview = [PreviewLocalFileHelper instantiation];
        [preview previewViewController:self localFile:model.filePath];
    }
    
    //键盘事件处理
    if(indexPath.section == 0) {
        UITableViewCell *tableCell = [tableView cellForRowAtIndexPath:indexPath];
        for (id view in tableCell.contentView.subviews) {
            if ([view isKindOfClass:[UITextField class]]) {
                UITextField *textField = view;
                [textField becomeFirstResponder];
            }
        }
    }
    
}

#pragma mark -
#pragma mark Button Event

- (void)delFileSelector:(GEObjectButton*)button
{
    NSArray *array = button.object;
    NSInteger section = [array[0] integerValue];
    id delValue = array[1];
    
    if (section == 1 && self.accessoryArray.count>0) {
        NSInteger index = [self.accessoryArray indexOfObject:delValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
        
        NSArray *delIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.accessoryArray removeObject:delValue];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:delIndexPath withRowAnimation:UITableViewRowAnimationLeft];
        [self.tableView endUpdates];
    }
    
}


#pragma mark -
#pragma mark BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    [super backResultDataKey:key dataValue:backValue];
    NSArray *array = backValue;
    if (!(array && array.count>0)) return;
    
    if([key isEqualToString:@"AccessoryFile"]){
        //添加附件
        if ([backValue isKindOfClass:[NSArray class]]) {
            NSMutableArray *insertIndexPath = [NSMutableArray array];
            for (int i=0;i<array.count;i++) {
                id value = [array objectAtIndex:i];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
                [insertIndexPath addObject:indexPath];
                [self.accessoryArray insertObject:value atIndex:0];
            }
            
            if (insertIndexPath.count>0) {
                [self.tableView beginUpdates];
                [self.tableView insertRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationTop];
                [self.tableView endUpdates];
            }
        }
    }
}


@end
